package com.inews.base.security.filter;

import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import com.inews.base.security.vo.BaseUserVo;

@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

	@Override
	public void decide(Authentication authentication, Object paramObject,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if(configAttributes == null) {  
            return;  
        }  
		
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();  
        while(iterator.hasNext()) {  
            ConfigAttribute configAttribute = iterator.next();  
            String needPermission = configAttribute.getAttribute();  
            for(GrantedAuthority ga : authentication.getAuthorities()) {  
                if(needPermission.equals(ga.getAuthority())) {
            		BaseUserVo baseUserVo = (BaseUserVo)authentication.getPrincipal();
            		FilterInvocation invocation = (FilterInvocation)paramObject;
            		String curttentAction = invocation.getRequestUrl();
            		baseUserVo.setCurrentAction(StringUtils.replace(curttentAction, "/", ""));
                    return;  
                }  
            }  
        }
        throw new AccessDeniedException("没有权限访问");  
	}

	@Override
	public boolean supports(ConfigAttribute paramConfigAttribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> paramClass) {
		return true;
	}

}
